package stock.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpOAuth2ServiceImpl;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import stock.properties.WxMpProperties;
import stock.service.impl.WechatServiceImpl;
import stock.utils.Result;

import java.util.*;

@RestController
@RequestMapping("wechat")
@Slf4j
public class WechatController {
    @Autowired
    WxMpProperties wxMpProperties;

    @Autowired
    WechatServiceImpl wechatService;

    @Autowired
    WxMpService wxMpService;

    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 跳转到授权地址  一般由前端实现
     * @param headers
     * @return
     */
    @GetMapping("/get/auth/url")
    public Result getAuthUrl(@RequestHeader Map<String,String> headers){
        System.out.println(headers);
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        String callback = "http://%s/wechat/wechat-login/callback";
        callback = String.format(callback,headers.get("host"));
        url = String.format(url, wxMpProperties.getAppId(),callback);
        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9ca8f216ea2719b9&redirect_uri=http://dev-music.quanyinzi.com/wechat/wechat-login/callback&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        return Result.success(url);
    }

    @GetMapping("/official/login")
    public Result officialLogin(@RequestParam("code") String code) {
        if (code == "") {
            return Result.error("code不能为空");
        }
        //======================自定义方法实现的===================
        Map<String,String> accessToken= (Map<String, String>) wechatService.getAccessToken(code);
        Map<String,String> userInfo= (Map<String, String>) wechatService.getUserInfo(accessToken.get("access_token"),accessToken.get("openid"));

        //======================SDK方法实现的===================
        try {
            System.out.println(wxMpService.getUserService().userInfo(accessToken.get("openid")));
        }catch (WxErrorException e){
            System.out.println(e);
        }

        redisTemplate.opsForHash().putAll("userinfo:"+accessToken.get("openid"),userInfo);
        return  Result.success(userInfo);

    }

    @GetMapping("/get/qrcode")
    public Result getQrcode(){
        Object result = null;
        try {
            result = wxMpService.getQrcodeService().qrCodePictureUrl("https://himg.bdimg.com/sys/portrait/item/public.1.1b043df2.Lwrisa5iuYshgxOXn45-wA.jpg");
            System.out.println(result);
        }catch (WxErrorException e){
            System.out.println(e);
        }
        return Result.success(result);
    }

    /**
     * 获取accessToken
     * @return
     */
    public String getAccessToken(){
        String token = null;
        try {
            token = wxMpService.getAccessToken();
        } catch (WxErrorException e) {
            System.out.println(e);
        }
        return token;
    }

    /**
     * 获取公众号 用户的openid
     * @return
     */
    @GetMapping("/get/mp/userlist")
    public Result getMpUserList(){
        //System.out.println(wxMpService.getUserService().userList());
        //{"total":12,"count":12,"openids":["oYUCe6kTxt9j45Br_1wh2R8nPwT0","oYUCe6nIfNMhp0WJgE_41KrEmer4","oYUCe6mBWUkYZPU3pGT1OSfy_SXs","oYUCe6isPVyqrgQBPO9TYIdHfwQA","oYUCe6nHAqGPNgCl2eQw2FCjcrqY","oYUCe6m8fQI4gTW8Cq8gx9loLXJ0","oYUCe6iBoAyWpDmnC_CRsi1hUyUY","oYUCe6uB6x2pjBE6gbOLsO9Rf7D0","oYUCe6ndw_QMXzyhcNy2nd-NkkHM","oYUCe6nSy4xlf2sZtmhWY4AD37Zs","oYUCe6jzOgoApz-1_Ce74HfwbPNA","oYUCe6uNmTNsiR9RQb1ubKy7bWt4"]}
        Object result = null;
        try {
            result = wxMpService.getUserService().userList();
        } catch (WxErrorException e) {
            System.out.println(e);
        }
        return Result.success(result);
    }

    @GetMapping("/send/templatemsg")
    public Result sendTemplateMsg(){
        String templateId = "xItHDqUS_lgCwxYDjIXGDhNeF2tXePGsMA1630KfEA";
        String openId = "oYUCe6kTxt9j45Br_1wh2R8nPwT0";

        //=================方式一==========
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateId);
        templateMessage.setToUser(openId);
        List<WxMpTemplateData> data = Arrays.asList(
                new WxMpTemplateData("keyword1","value"),
                new WxMpTemplateData("keyword2","你好1"),
                new WxMpTemplateData("keyword3","你好2"),
                new WxMpTemplateData("keyword4","你好3","#ff0000"),
                new WxMpTemplateData("keyword5","你好4","#0000ff"),
                new WxMpTemplateData("remark","备注")
        );
        for(WxMpTemplateData item: data){
            System.out.println(item);
            templateMessage.addData(item);
        }
        //=================方式二==========
//        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder().templateId(templateId).toUser(openId).build();

//        templateMessage.addData(new WxMpTemplateData("first","标题"));
//        templateMessage.addData(new WxMpTemplateData("keyword1","value"));
//        templateMessage.addData(new WxMpTemplateData("keyword2","你好1"));
//        templateMessage.addData(new WxMpTemplateData("keyword3","你好2"));
//        templateMessage.addData(new WxMpTemplateData("keyword4","你好3","#ff00ff"));
//        templateMessage.addData(new WxMpTemplateData("keyword5","你好4","#0000ff"));
//        templateMessage.addData(new WxMpTemplateData("remark","备注"));

        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        }catch (WxErrorException e){
            System.out.println(e);
        }
        return Result.success();
    }
//    public WxMpTemplateMessage build(String templateIdString,JSONObject data, String openId) {
//        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
//                .toUser(openId)
//                // 用户openid
//                .templateId(templateIdString) // 模板消息ID
//                .build();
//        templateMessage.addData(new WxMpTemplateData("first", "今日天气"));
//        try {
//            Iterator<String> keys = data.keys();
//            while (keys.hasNext()) {
//                String key = keys.next();
//                String value = null;
//                value = data.getString(key);
//                WxMpTemplateData templateData = new WxMpTemplateData(key, value);
//                templateMessage.addData(templateData);
//            }
//        } catch () {
//
//        }
//    }
    @RequestMapping("/msg/handle")
    public String send(@RequestBody String requestBody, @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
        // 校验签名
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            log.error("签名校验 ===》 非法请求");
            // 消息签名不正确，说明不是公众平台发过来的消息
            return null;
        }
        log.error("签名校验 ===》 验证成功");

        // 解析消息体，封装为对象
        WxMpXmlMessage xmlMessage = WxMpXmlMessage.fromXml(requestBody);
        // 接收消息内容
        String inContent = xmlMessage.getContent();

        // 响应的消息内容
        String outContent;
        // 根据不同的关键字回复消息
        if (inContent.contains("hello")) {
            outContent = "hello world";
        } else if (inContent.contains("java")) {
            outContent = "hello java";
        } else {
            outContent = "服务繁忙,暂时不能回复";
        }

        // 构造响应消息对象
        WxMpXmlOutTextMessage outTextMessage = WxMpXmlOutMessage.TEXT().content(outContent).fromUser(xmlMessage.getToUser())
                .toUser(xmlMessage.getFromUser()).build();

        // 将响应消息转换为xml格式返回
        return outTextMessage.toXml();
    }

}
